package ai.taromed.vr;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import ai.taromed.vr.menu.FilterMenu;
import ai.taromed.vr.menu.FilterMenuLayout;


public class PlayerActivity extends AppCompatActivity {

    public static final String TAG = "PlayerActivity";

    public static final String CONFIG_BUNDLE = "activity_configBundle";

    private ConfigBundle configBundle ;

    private FilterMenuLayout filter_menu1;
    private FilterMenu filterMenu;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);


        setContentView(R.layout.layout_player_activity);

        configBundle= (ConfigBundle) getIntent().getSerializableExtra(CONFIG_BUNDLE);

        if(configBundle==null){
            throw new RuntimeException("config can't be null");
        }

        initVideos();
        initMenu();
        initFragment();
    }


    private ArrayList<String> videos = new ArrayList<String>();
    private void initVideos(){
        String basePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        Log.e(TAG , "-------basePath:" + basePath);
        videos.add(basePath + "/taromed/FactoryEntrance.mp4");
        videos.add(basePath + "/taromed/SaftyIntroduction.mp4");
        videos.add(basePath + "/taromed/TaromedIntroduction.mp4");
        videos.add(basePath + "/taromed/Warehouse.mp4");
        videos.add(basePath + "/taromed/ManufactureRoom.mp4");
        videos.add(basePath + "/taromed/TestRoom.mp4");
    }

    private void initMenu(){
        filter_menu1 = (FilterMenuLayout) findViewById(R.id.filter_menu1);
        FilterMenu.OnMenuChangeListener listener = new FilterMenu.OnMenuChangeListener() {
            @Override
            public void onMenuItemClick(View view, int position) {
                if(filterMenu == null){
                    return;
                }
                List<FilterMenu.Item> menus = filterMenu.getItems();
                FilterMenu.Item item = menus.get(position);
                if(item.isBottom()){
                    finish();
                }else{
                    String video_path = videos.get(position);
                    if(!new File(video_path).exists()){
                        Toast.makeText(PlayerActivity.this , "the video is not exist!" , Toast.LENGTH_SHORT).show();
                        return;
                    }
                    configBundle.setFilePath(video_path);
                    initFragment();
                    Log.e(TAG , "--------video_path： "+ video_path);
                }
            }
            @Override
            public void onMenuCollapse() { }
            @Override
            public void onMenuExpand() {}
        };

        View backView = View.inflate(PlayerActivity.this ,R.layout.layout_menu_back  , null);
        filterMenu = new FilterMenu.Builder(this)
                .addItem(R.string.Factory_Entrance)
                .addItem(R.string.Safty_Introduction)
                .addItem(R.string.Taromed_Introduction)
                .addItem(R.string.Warehouse)
                .addItem(R.string.Manufacture_Room)
                .addItem(R.string.Test_Room)
                .addBackItem(backView)
                .attach(filter_menu1)
                .withListener(listener)
                .build();

        filterMenu.changeMenuItemBg(configBundle.getMenuIndex());
    }



    private PlayerFragment currentFragment;

    private void initFragment(){
        currentFragment = new PlayerFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(PlayerFragment.CONFIG_BUNDLE, configBundle);
        currentFragment.setArguments(bundle);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fl_fragment , currentFragment);
        transaction.commit();

    }



    private void spyOnKeyEvent(){

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int repeatCount = event.getRepeatCount();
        switch(keyCode){
              case  KeyEvent.KEYCODE_DPAD_LEFT:
                  if(repeatCount > 0 && currentFragment != null){
                      spyHandler.sendEmptyMessage(SpyHandler.ON_KEY_EVENT_LEFT_WHAT);
                  }
                  break;
              case  KeyEvent.KEYCODE_DPAD_RIGHT:
                  if(repeatCount > 0 && currentFragment != null){
                      spyHandler.sendEmptyMessage(SpyHandler.ON_KEY_EVENT_RIGHT_WHAT);
                  }
                  break;

            case  KeyEvent.KEYCODE_DPAD_UP:
                if(repeatCount > 0 && currentFragment != null){
                    spyHandler.sendEmptyMessage(SpyHandler.ON_KEY_EVENT_UP_WHAT);
                }
                break;
            case  KeyEvent.KEYCODE_DPAD_DOWN:
                if(repeatCount > 0 && currentFragment != null){
                    spyHandler.sendEmptyMessage(SpyHandler.ON_KEY_EVENT_BOTTOM_WHAT);
                }
                break;
        }
        Log.e(TAG , "-----keyCode:" + keyCode + " , ----event:" + event.toString());
        return super.onKeyDown(keyCode, event);
    }


    private SpyHandler spyHandler = new SpyHandler();

    class SpyHandler extends Handler{

        public static final int ON_KEY_EVENT_LEFT_WHAT = 1000;
        public static final int ON_KEY_EVENT_RIGHT_WHAT = 1001;
        public static final int ON_KEY_EVENT_UP_WHAT = 1002;
        public static final int ON_KEY_EVENT_BOTTOM_WHAT = 1003;
        public static final int ON_RESET_WHAT = 1004;

        public SpyHandler(){
            super();
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if(what == ON_KEY_EVENT_LEFT_WHAT){
                removeMessages(ON_RESET_WHAT);
                currentFragment.rotateByGameHandle(-60f,0f);
                sendEmptyMessageDelayed(ON_RESET_WHAT , 300);
            }else if(what == ON_KEY_EVENT_RIGHT_WHAT){
                removeMessages(ON_RESET_WHAT);
                currentFragment.rotateByGameHandle(60f,0f);
                sendEmptyMessageDelayed(ON_RESET_WHAT , 300);
            }else if(what == ON_KEY_EVENT_UP_WHAT){
                removeMessages(ON_RESET_WHAT);
                currentFragment.rotateByGameHandle(0f,-60f);
                sendEmptyMessageDelayed(ON_RESET_WHAT , 300);
            }else if(what == ON_KEY_EVENT_BOTTOM_WHAT){
                removeMessages(ON_RESET_WHAT);
                currentFragment.rotateByGameHandle(0f,60f);
                sendEmptyMessageDelayed(ON_RESET_WHAT , 300);
            }else if(what == ON_RESET_WHAT){
                currentFragment.resetManunalHandle();
            }

        }
    }




}
